package cn.zzzhy.core.db;

import cn.zzzhy.core.db.builder.ISQLBuilder;
import cn.zzzhy.core.util.Util;
import com.google.common.base.CaseFormat;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

/**
 * author:zzzhy
 * since :15/11/9.
 */
public class Query {


    private final DB db;
    private final JdbcTemplate jdbcTemplate;
    private final ISQLBuilder sqlBuilder;

    public Query(DB db, JdbcTemplate jdbcTemplate, ISQLBuilder sqlBuilder) {
        this.db = db;
        this.jdbcTemplate = jdbcTemplate;
        this.sqlBuilder = sqlBuilder;
    }

    public Query from(String tableName) {
        sqlBuilder.setTable(tableName);
        return this;
    }

    public Query from(Class<?> clazz){
        String tableName = clazz.getSimpleName();
        sqlBuilder.setTable(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,tableName));
        return this;
    }

    public Query join(String joinString){
        sqlBuilder.join(joinString);
        return this;
    }


    public <T> T first(Class<T> entity) {
        sqlBuilder.limit(0,1);
        List<T> list = doQuery(entity,null);
        if(list == null || list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    public <T> List<T> all(Class<T> clazz) {
        return doQuery(clazz, null);
    }

    private <T> List<T> doQuery(Class<T> clazz, RowMapper<T> rowMapper) {
        List<T> data;
        if (Util.isPrimitive(clazz)) {
            data = jdbcTemplate.queryForList(sqlBuilder.toSQL(),
                    sqlBuilder.getParameters(), clazz);
        } else {
            if (rowMapper == null) {
                rowMapper = db.buildRowMapper(clazz);
            }

            data = jdbcTemplate.query(sqlBuilder.toSQL(),
                    sqlBuilder.getParameters(), rowMapper);
        }
        return data;
    }

}
